package com.ytjj.qmyx.admin.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.SmsErrorDescDao;
import com.ytjj.qmyx.admin.dao.SmsSenderRecordsDao;
import com.ytjj.qmyx.admin.mapper.AdminMapper;
import com.ytjj.qmyx.admin.mapper.SmsSenderRecordsMapper;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.AdminExample;
import com.ytjj.qmyx.admin.model.request.SendSMSRequest;
import com.ytjj.qmyx.admin.model.request.SmsSenderRecordsRequest;
import com.ytjj.qmyx.admin.model.request.SmsTemplateRequest;
import com.ytjj.qmyx.admin.model.response.SmsPreviewContentResponse;
import com.ytjj.qmyx.admin.model.response.SmsSenderRecordsResponse;
import com.ytjj.qmyx.admin.model.response.SmsTemplateResponse;
import com.ytjj.qmyx.admin.model.sms.SmsErrorDesc;
import com.ytjj.qmyx.admin.model.sms.SmsSenderRecords;
import com.ytjj.qmyx.admin.model.sms.SmsSenderRecordsExample;
import com.ytjj.qmyx.admin.model.sms.SmsTemplate;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.admin.service.SmsManageService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.mapper.MsgFailLogMapper;
import com.ytjj.qmyx.mall.model.MsgFailLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author jiawei
 * @date 2023年04月18日 15:07
 * @describe
 */
@Slf4j
@Service
public class SmsManageServiceImpl implements SmsManageService {

    @Resource
    private SmsSenderRecordsDao smsSenderRecordsDao;
    @Resource
    private SmsSenderRecordsMapper smsSenderRecordsMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private SmsErrorDescDao smsErrorDescDao;
    @Resource
    private MsgFailLogMapper msgFailLogMapper;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private MemberService memberService;

    ThreadPoolExecutor pools = new ThreadPoolExecutor(10, 20, 5,TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

    @Override
    public Integer addOrEditTemplate(SmsTemplate smsTemplate) {
        Admin admin = UserUtil.getAdmin();
        //修改
        if (null != smsTemplate.getId()) {
            smsTemplate.setUpdateId(admin.getId());
        }
        //新增
        else {
            smsTemplate.setCreateId(admin.getId());
        }
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/addOrEditTemplate",
                JSONObject.toJSONString(smsTemplate), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
        if (null == commonResult) {
            throw new ApiException("系统异常，请反馈！");
        } else if (!"200".equals(String.valueOf(commonResult.getCode()))) {
            throw new ApiException(commonResult.getMessage());
        } else {
            return 1;
        }
    }

    @Override
    public CommonResult changeStatus(Integer id, Integer status) {
        Map<String, String> map = new HashMap<>();
        map.put("id", id.toString());
        map.put("status", status.toString());
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/smsManage/changeStatus", map);
        CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
        return commonResult;
    }


    @Override
    public CommonResult delete(Integer id) {
        Map<String, String> map = new HashMap<>();
        map.put("id",id.toString());
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/smsManage/delete",map);
        CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
        return commonResult;
    }

    @Override
    public CommonPage<SmsTemplateResponse> getTemplateOnePage(SmsTemplateRequest request) {
        Admin loginAdmin = memberService.getAdmin();
        List<SmsTemplateResponse> newData = new ArrayList<>();
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/getTemplateOnePage",
                JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
        if (null == commonResult){
            throw new ApiException("系统异常，请反馈！");
        }else if(!"200".equals(String.valueOf(commonResult.getCode()))) {
            throw new ApiException(commonResult.getMessage());
        }else {
            Object data = commonResult.getData();
            CommonPage commonPage = JSON.parseObject(JSON.toJSONString(data), CommonPage.class);
            List list = commonPage.getList();
            if(!CollectionUtils.isEmpty(list)){
                List<SmsTemplate> smsTemplates = JSON.parseArray(JSON.toJSONString(list), SmsTemplate.class);
                Set<Integer> adminIds = new HashSet<>();
                adminIds.addAll(smsTemplates.stream().map(e -> e.getCreateId()).collect(Collectors.toSet()));
                adminIds.addAll(smsTemplates.stream().map(e -> e.getUpdateId()).collect(Collectors.toSet()));
                AdminExample adminExample = new AdminExample();
                adminExample.createCriteria().andIdIn(new ArrayList<>(adminIds));
                List<Admin> admins = adminMapper.selectByExample(adminExample);
                Map<Integer, Admin> adminMap = admins.stream().collect(Collectors.toMap(e -> e.getId(), Function.identity()));
                smsTemplates.stream().forEach(e->{
                    SmsTemplateResponse smsTemplateResponse = new SmsTemplateResponse();
                    BeanUtils.copyProperties(e,smsTemplateResponse);
                    Admin admin = adminMap.get(e.getCreateId());
                    Admin updateAdmin = adminMap.get(e.getUpdateId());
                    smsTemplateResponse.setCreateName(null == admin ? null : admin.getName());
                    smsTemplateResponse.setUpdateName(null == updateAdmin ? null : updateAdmin.getName());
                    String s = redisService.get(RedisConstants.MSG_TEMPLATE_VARIABLE_KEY + ":" + e.getId() + ":" + loginAdmin.getId());
                    List<String> strings = JSON.parseArray(s, String.class);
                    smsTemplateResponse.setPlaceHolders(strings);
                    newData.add(smsTemplateResponse);
                });
            }
            CommonPage<SmsTemplateResponse> smsTemplateResponseCommonPage = CommonPage.restPage(newData);
            smsTemplateResponseCommonPage.setTotal(commonPage.getTotal());
            smsTemplateResponseCommonPage.setTotalPage(commonPage.getTotalPage());
            smsTemplateResponseCommonPage.setPageNum(commonPage.getPageNum());
            smsTemplateResponseCommonPage.setPageSize(commonPage.getPageSize());

            return smsTemplateResponseCommonPage;
        }
    }

    @Override
    public CommonPage<SmsSenderRecordsResponse> getSmsSendRecordsOnePage(SmsSenderRecordsRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SmsSenderRecordsResponse> smsSendRecords = smsSenderRecordsDao.getSmsSendRecords(request);
        Map<String, SmsErrorDesc> allErrorDesc = smsErrorDescDao.getAllErrorDesc().stream().collect(Collectors.toMap(e -> e.getCode(), Function.identity()));
        smsSendRecords.stream().forEach(e -> {
            if (StringUtils.isNotEmpty(e.getCode())) {
                SmsErrorDesc smsErrorDesc = allErrorDesc.get(e.getCode());
                if (null != smsErrorDesc && e.getSmsSource().equals(smsErrorDesc.getType())) {
                    e.setMessage(smsErrorDesc.getDetailDesc());
                }
            }
        });
        CommonPage<SmsSenderRecordsResponse> smsSenderRecordsResponseCommonPage = CommonPage.restPage(smsSendRecords);
        return smsSenderRecordsResponseCommonPage;
    }

    @Override
    public CommonPage<SmsSenderRecordsResponse> getSysSmsSendRecordsOnePage(SmsSenderRecordsRequest request) {
        List<SmsSenderRecordsResponse> smsSendRecords = new ArrayList<>();
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<MsgFailLog> msgFailLogs = msgFailLogMapper.getSmsSendRecords(request.getContent(), request.getStatus(), request.getPhone(), request.getStartTime(), request.getEndTime(),request.getSmsType());
        List<Integer> ids = msgFailLogs.stream().map(e -> e.getId()).collect(Collectors.toList());
        Map<Integer, SmsSenderRecords> collect = new HashMap<>();
        if(!CollectionUtils.isEmpty(ids)){
            SmsSenderRecordsExample example = new SmsSenderRecordsExample();
            example.createCriteria().andMsgLogIdIn(ids);
            List<SmsSenderRecords> smsSenderRecords = smsSenderRecordsMapper.selectByExample(example);
            collect = smsSenderRecords.stream().collect(Collectors.toMap(e -> e.getMsgLogId(), Function.identity()));
        }
        for (MsgFailLog msgFailLog : msgFailLogs) {
            SmsSenderRecordsResponse smsSenderRecordsResponse = new SmsSenderRecordsResponse();
            smsSenderRecordsResponse.setPhone(msgFailLog.getPhone());
            smsSenderRecordsResponse.setSmsType(null != msgFailLog.getType() ? Integer.valueOf(msgFailLog.getType()) : null);
            smsSenderRecordsResponse.setContent(msgFailLog.getContent());
            smsSenderRecordsResponse.setCode(msgFailLog.getCode());
            smsSenderRecordsResponse.setStatus(msgFailLog.getStatus().intValue());
            smsSenderRecordsResponse.setId(msgFailLog.getId());
            smsSenderRecordsResponse.setCreateTime(msgFailLog.getCreateTime());
            smsSenderRecordsResponse.setSmsSource(msgFailLog.getSmsSource());
            SmsSenderRecords smsSenderRecords = collect.get(msgFailLog.getId());
            smsSenderRecordsResponse.setSendingSource(null != smsSenderRecords ? 1 : 2);
//            smsSenderRecordsResponse.set(null != smsSenderRecords ? 1 : 2);
            smsSendRecords.add(smsSenderRecordsResponse);
        }
        CommonPage<SmsSenderRecordsResponse> smsSenderRecordsResponseCommonPage = CommonPage.restPage(smsSendRecords);
        return smsSenderRecordsResponseCommonPage;
    }

    @Override
    public List<String> userSendSmsByTemplate(SendSMSRequest sendSMSRequest) {
        matchPhoneList(sendSMSRequest.getPhone());
        Admin admin = UserUtil.getAdmin();
        Integer templateId = sendSMSRequest.getTemplateId();
        if (null == templateId) {
            throw new ApiException("短信模板不能为空！");
        }
        SmsTemplate smsTemplate = new SmsTemplate();
        SmsTemplateRequest request = new SmsTemplateRequest();
        request.setId(templateId);
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/getTemplateOnePage",
                JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
        if (null == commonResult){
            throw new ApiException("系统异常，请反馈！");
        }else if(!"200".equals(String.valueOf(commonResult.getCode()))) {
            throw new ApiException(commonResult.getMessage());
        }else {
            Object data = commonResult.getData();
            CommonPage commonPage = JSON.parseObject(JSON.toJSONString(data), CommonPage.class);
            List list = commonPage.getList();
            List<SmsTemplate> smsTemplates = JSON.parseArray(JSON.toJSONString(list), SmsTemplate.class);
            if(CollectionUtils.isEmpty(smsTemplates)){
                throw new ApiException("模板不存在！");
            }
            smsTemplate = smsTemplates.get(0);
        }
        if (smsTemplate.getStatus() == 0) {
            throw new ApiException("短信模板未启用！");
        }
        String content = smsTemplate.getContent();
        List<String> strings = matchCharacter(content);
        //占位符变量集合
        List<String> placeholders = new ArrayList<>();
        for (int i = 0; i < strings.size(); i++) {
            String placeholder = strings.get(i).replace("{", "").replace("}", "");
            String placeholderContent = sendSMSRequest.getVariables().get(i);
            if (StringUtils.isBlank(placeholderContent)) {
                content = content.replaceFirst(Pattern.quote(strings.get(i)), "");
                continue;
            }
            String[] placeholderIndex = placeholder.split(",");
            int startIndex = Integer.valueOf(placeholderIndex[0]);
            int endIndex = Integer.valueOf(placeholderIndex[1]);
            //不符合格式{X,X}
            if (placeholderIndex.length != 2) {
                throw new ApiException("请正确填写短信内容中的变量！");
            }
            //根据占位符的长度，截取输入字符的长度
            if (placeholderContent.length() < endIndex) {
                endIndex = placeholderContent.length();
            }
            if (placeholderContent.length() < startIndex) {
                startIndex = placeholderContent.length();
            }
            String variables = placeholderContent.substring(startIndex, endIndex);
            content = content.replaceFirst(Pattern.quote(strings.get(i)), variables);
            placeholders.add(variables);
        }
        //保存输截取后的字符串到缓存，方便下次用
        redisService.set(RedisConstants.MSG_TEMPLATE_VARIABLE_KEY + ":" + smsTemplate.getId() + ":" + admin.getId(), JSON.toJSONString(placeholders));
        if (!sendSMSRequest.getContent().equals(content)) {
            throw new ApiException("短信预览内容和系统解析内容不一致！");
        }
        List<String> successSms = new ArrayList<>();
        try {
            SmsTemplate finalSmsTemplate = smsTemplate;
            sendSMSRequest.getPhone().stream().forEach(e -> {
                //保存记录
                SmsSenderRecords smsSenderRecords = new SmsSenderRecords();
                smsSenderRecords.setCreateTime(new Date());
                smsSenderRecords.setContent(finalSmsTemplate.getSign() + sendSMSRequest.getContent());
                smsSenderRecords.setPhone(e);
                smsSenderRecords.setOperatorId(admin.getId());
                smsSenderRecords.setSmsType(2);
                smsSenderRecords.setSendWay(1);
                smsSenderRecordsMapper.insertSelective(smsSenderRecords);
                SmsDto dto = new SmsDto();
                dto.setType(8);
                dto.setPhone(e);
                dto.setOrderId(smsSenderRecords.getId());
                dto.setCode(sendSMSRequest.getContent());
                dto.setChannel(finalSmsTemplate.getSign());
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
                successSms.add(e);
            });
        } catch (Exception e) {
            log.error("使用短信模板发送失败！{}", e);
        } finally {
            //未成功发送的数量
            sendSMSRequest.getPhone().removeAll(successSms);
        }
        return sendSMSRequest.getPhone();
    }

    @Override
    public List<String> userSendSmsFreedom(SendSMSRequest sendSMSRequest) {
        matchPhoneList(sendSMSRequest.getPhone());
        Admin admin = UserUtil.getAdmin();
        Assert.notNull(sendSMSRequest.getSign(), "签名不能为空！");
        Assert.notNull(sendSMSRequest.getContent(), "短信内容不能为空！");
        //校验签名
        List<String> allSign = getAllSign();
        boolean exist = allSign.contains(sendSMSRequest.getSign());
        if (!exist) {
            throw new ApiException("短信签名不存在！");
        }
        //成功短信数量
        List<String> successSms = new ArrayList<>();
        try {
            sendSMSRequest.getPhone().stream().forEach(e -> {
                //保存记录
                SmsSenderRecords smsSenderRecords = new SmsSenderRecords();
                smsSenderRecords.setCreateTime(new Date());
                smsSenderRecords.setContent(sendSMSRequest.getSign() + sendSMSRequest.getContent());
                smsSenderRecords.setPhone(e);
                smsSenderRecords.setOperatorId(admin.getId());
                smsSenderRecords.setSmsType(1);
                smsSenderRecords.setSendWay(1);
                smsSenderRecordsMapper.insertSelective(smsSenderRecords);
                SmsDto dto = new SmsDto();
                dto.setType(8);
                dto.setPhone(e);
                dto.setOrderId(smsSenderRecords.getId());
                dto.setCode(sendSMSRequest.getContent());
                dto.setChannel(sendSMSRequest.getSign());
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
                successSms.add(e);
            });
        } catch (Exception e) {
            log.error("使用自定义短信发送失败！{}", e);
        } finally {
            //未成功发送的数量
            sendSMSRequest.getPhone().removeAll(successSms);
        }
        return sendSMSRequest.getPhone();
    }




    /**
     * 正则匹配占位符
     *
     * @param content 待匹配的内容
     * @return Integer
     */
    public List<String> matchCharacter(String content) {
        List<String> charaList = new ArrayList<>();
        if (StringUtils.isNotEmpty(content)) {
            Pattern pattern = Pattern.compile("\\{(\\d+,\\d+)\\}");
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                String group = matcher.group();
                group = group.replaceFirst("，", ",");
                charaList.add(group);
                log.info("匹配到短信内容的占位符是：" + group);
            }
        }
        return charaList;
    }

    /**
     * 校验手机号码是否正确
     *
     * @param phones 待验证的手机号
     * @return Integer
     */
    public void matchPhoneList(List<String> phones) {
        List<String> errorPhone = new ArrayList<>();
        if (!CollectionUtils.isEmpty(phones)) {
            for (String phone : phones) {
                Pattern pattern = Pattern.compile("1[3-9]\\d{9}");
                Matcher matcher = pattern.matcher(phone);
                if (!matcher.matches()) {
                    errorPhone.add(phone);
                }
            }
            if (!CollectionUtils.isEmpty(errorPhone)) {
                throw new ApiException("下列手机号码格式错误：" + String.join(",", errorPhone));
            }
        }
    }

    public static void main(String[] args) {
        String s = "{1,2,3}";
//        String s = null;
        //正则匹配： https://mall.XXXX.com/
        Pattern pattern = Pattern.compile("\\{(\\d+[,，]\\d+)\\}");
        Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            String group = matcher.group();
            group = group.replaceFirst("，", ",");
            System.out.println("----->" + group);
        }

//        Pattern pattern = Pattern.compile("1[3-9]\\d{9}");
//        Matcher matcher = pattern.matcher(s);
//        System.out.println("当前字符"+matcher.matches());

    }

    @Override
    public String previewSmsContent(SendSMSRequest sendSMSRequest) {
        String previewContent = "";
        if (sendSMSRequest.getSmsType() == 1) {
            previewContent = sendSMSRequest.getSign() + sendSMSRequest.getContent();
        } else if (sendSMSRequest.getSmsType() == 2) {
            SmsTemplate smsTemplate = new SmsTemplate();
            SmsTemplateRequest request = new SmsTemplateRequest();
            request.setId(sendSMSRequest.getTemplateId());
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/getTemplateOnePage",
                    JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
            CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
            if (null == commonResult){
                throw new ApiException("系统异常，请反馈！");
            }else if(!"200".equals(String.valueOf(commonResult.getCode()))) {
                throw new ApiException(commonResult.getMessage());
            }else {
                Object data = commonResult.getData();
                CommonPage commonPage = JSON.parseObject(JSON.toJSONString(data), CommonPage.class);
                List list = commonPage.getList();
                List<SmsTemplate> smsTemplates = JSON.parseArray(JSON.toJSONString(list), SmsTemplate.class);
                if(CollectionUtils.isEmpty(smsTemplates)){
                    throw new ApiException("模板不存在！");
                }
                smsTemplate = smsTemplates.get(0);
            }
            String content = smsTemplate.getContent();
            List<String> strings = matchCharacter(content);
            for (int i = 0; i < strings.size(); i++) {
                String placeholder = strings.get(i).replace("{", "").replace("}", "");
                String placeholderContent = sendSMSRequest.getVariables().get(i);
                String[] placeholderIndex = placeholder.split(",");
                int startIndex = Integer.valueOf(placeholderIndex[0]);
                int endIndex = Integer.valueOf(placeholderIndex[1]);
                if (placeholderContent.length() < endIndex) {
                    endIndex = placeholderContent.length();
                }
                String variables = placeholderContent.substring(startIndex, endIndex);
                content = content.replaceFirst(Pattern.quote(strings.get(i)), variables);
            }
            previewContent = smsTemplate.getSign() + content;
        }
        return previewContent;
    }

    @Override
    public SmsPreviewContentResponse previewImportSmsContent(MultipartFile file, Integer smsType, Integer templateId) {
        SmsPreviewContentResponse responseDate = new SmsPreviewContentResponse();
        // 解析
        Sheet sheet = new Sheet(1, 1);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            if (CollectionUtils.isEmpty(list)) {
                throw new ApiException("数据不能为空！");
            }
            if (list.size() > 1000) {
                throw new ApiException("最大支持1000条批量发送！");
            }
            //预览数据
            List<Map<String,Object>> previewList = new ArrayList<>();
            //错误数据
            List<String> errorData = new ArrayList<>();
            //重复数据
            List<String> duplicateData = new ArrayList<>();
            responseDate.setImportTotal(list.size());
            String errorContent = "手机号:%s，%s";
            if (smsType == 1) {
                for (int i = 0; i < list.size(); i++) {
                    List<String> lineData = JSON.parseArray(JSON.toJSONString(list.get(i)), String.class);
                    String phone = lineData.get(0);
                    //excel格式不对，或列的数据为空
                    if (lineData.size() != 3) {
                        if(null != phone){
                            errorData.add(String.format(errorContent,phone,"数据不完整"));
                        }else {
                            errorData.add("手机号不能为空！");
                        }
                        continue;
                    }
                    try {
                        //校验手机号
                        matchPhoneList(Arrays.asList(phone));
                    } catch (Exception e) {
                        errorData.add(String.format(errorContent, phone, "手机格式不正确!"));
                        continue;
                    }
                    Map<String,Object> lineMap = new HashMap<>();
                    lineMap.put("phone",phone);
                    lineMap.put("sign",lineData.get(1));
                    lineMap.put("content",lineData.get(2));
                    //是否重复数据
                    boolean isDuplicate = false;
                    for (Map<String, Object> stringObjectMap : previewList) {
                        if(phone.equals(stringObjectMap.get("phone").toString()) && (lineData.get(1)+lineData.get(2)).equals(stringObjectMap.get("content").toString())){
                            duplicateData.add(stringObjectMap.get("phone").toString());
                            isDuplicate = true;
                            break;
                        }
                    }
                    if(isDuplicate){
                        continue;
                    }
                    previewList.add(lineMap);
                }
            } else if (smsType == 2) {
                SmsTemplate smsTemplate = new SmsTemplate();
                SmsTemplateRequest request = new SmsTemplateRequest();
                request.setId(templateId);
                String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/getTemplateOnePage",
                        JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
                CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
                if (null == commonResult){
                    throw new ApiException("系统异常，请反馈！");
                }else if(!"200".equals(String.valueOf(commonResult.getCode()))) {
                    throw new ApiException(commonResult.getMessage());
                }else {
                    Object data = commonResult.getData();
                    CommonPage commonPage = JSON.parseObject(JSON.toJSONString(data), CommonPage.class);
                    List dataList = commonPage.getList();
                    List<SmsTemplate> smsTemplates = JSON.parseArray(JSON.toJSONString(dataList), SmsTemplate.class);
                    if(CollectionUtils.isEmpty(smsTemplates)){
                        throw new ApiException("模板不存在！");
                    }
                    smsTemplate = smsTemplates.get(0);
                }
                if (smsTemplate.getStatus() == 0) {
                    throw new ApiException("短信模板未启用！");
                }
                for (int i = 0; i < list.size(); i++) {
                    List<String> lineData = JSON.parseArray(JSON.toJSONString(list.get(i)), String.class);
                    //excel格式不对，或列的数据为空
                    String phone = lineData.get(0);
                    if (null == phone) {
                        errorData.add("手机号不能为空！");
                        continue;
                    }
                    try {
                        //校验手机号
                        matchPhoneList(Arrays.asList(phone));
                    } catch (Exception e) {
                        errorData.add(String.format(errorContent, phone, "手机格式不正确!"));
                        continue;
                    }
                    //短信内容
                    String content = smsTemplate.getContent();
                    List<String> strings = matchCharacter(content);
                    for (int j = 0; j < strings.size(); j++) {
                        String placeholderContent = "";
                        //j+1:从手机号这一列开始算
                        if (j + 1 <= lineData.size() - 1) {
                            placeholderContent = lineData.get(j + 1);
                        }
                        if (StringUtils.isBlank(placeholderContent)) {
                            content = content.replaceFirst(Pattern.quote(strings.get(j)), "");
                            continue;
                        }
                        String placeholder = strings.get(j).replace("{", "").replace("}", "");
                        String[] placeholderIndex = placeholder.split(",");
                        int startIndex = Integer.valueOf(placeholderIndex[0]);
                        int endIndex = Integer.valueOf(placeholderIndex[1]);
                        //不符合格式{X,X}
                        if (placeholderIndex.length != 2) {
                            throw new ApiException("请正确填写短信内容中的变量！");
                        }
                        if (placeholderContent.length() < endIndex) {
                            endIndex = placeholderContent.length();
                        }
                        if (placeholderContent.length() < startIndex) {
                            startIndex = placeholderContent.length();
                        }
                        content = content.replaceFirst(Pattern.quote(strings.get(j)), placeholderContent.substring(startIndex, endIndex));
                    }
                    Map<String,Object> lineMap = new HashMap<>();
                    lineMap.put("phone",phone);
                    lineMap.put("sign",smsTemplate.getSign());
                    lineMap.put("content",content);
                    boolean isDuplicate = false;
                    for (Map<String, Object> itemMap : previewList) {
                        if(phone.equals(itemMap.get("phone").toString()) && (content).equals(itemMap.get("content").toString())){
                            duplicateData.add(itemMap.get("phone").toString());
                            isDuplicate = true;
                            break;
                        }
                    }
                    if(isDuplicate){
                        continue;
                    }
                    previewList.add(lineMap);
                }
            }
            responseDate.setSuccessTotal(previewList.size());
            responseDate.setDuplicateData(duplicateData);
            responseDate.setErrorData(errorData);
            responseDate.setPreviewList(previewList);
            log.info("表格数据：{}", JSONObject.toJSONString(list));
        } catch (Exception e) {
            log.info("导入发生异常：{}", e);
        }
        return responseDate;
    }

    @Override
    public CommonResult sendImportSms(MultipartFile file, Integer smsType, Integer templateId) {
        Admin admin = UserUtil.getAdmin();
        SmsPreviewContentResponse smsPreviewContentResponse = previewImportSmsContent(file, smsType, templateId);
        if(null == smsType){
            throw new ApiException("参数错误！");
        }
        if(smsType == 2){
            if (null == templateId) {
                throw new ApiException("短信模板不能为空！");
            }
            SmsTemplateRequest request = new SmsTemplateRequest();
            request.setId(templateId);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/smsManage/getTemplateOnePage",
                    JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
            CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
            if (null == commonResult){
                throw new ApiException("系统异常，请反馈！");
            }else if(!"200".equals(String.valueOf(commonResult.getCode()))) {
                throw new ApiException(commonResult.getMessage());
            }else {
                Object data = commonResult.getData();
                CommonPage commonPage = JSON.parseObject(JSON.toJSONString(data), CommonPage.class);
                List list = commonPage.getList();
                List<SmsTemplate> smsTemplates = JSON.parseArray(JSON.toJSONString(list), SmsTemplate.class);
                if(CollectionUtils.isEmpty(smsTemplates)){
                    throw new ApiException("模板不存在！");
                }
                SmsTemplate smsTemplate = smsTemplates.get(0);
                if (smsTemplate.getStatus() == 0) {
                    throw new ApiException("短信模板未启用！");
                }
            }
        }
        List<Map<String, Object>> previewList = smsPreviewContentResponse.getPreviewList();
        previewList.stream().forEach(e -> {
            pools.execute(() -> {
                String phone = e.get("phone").toString();
                String content = e.get("content").toString();
                String sign = e.get("sign").toString();
                //保存记录
                SmsSenderRecords smsSenderRecords = new SmsSenderRecords();
                smsSenderRecords.setCreateTime(new Date());
                smsSenderRecords.setContent(sign+content);
                smsSenderRecords.setPhone(phone);
                smsSenderRecords.setOperatorId(admin.getId());
                smsSenderRecords.setSmsType(smsType);
                smsSenderRecords.setSendWay(2);
                smsSenderRecordsMapper.insertSelective(smsSenderRecords);
                SmsDto dto = new SmsDto();
                dto.setType(8);
                dto.setPhone(phone);
                dto.setOrderId(smsSenderRecords.getId());
                dto.setCode(content);
                dto.setChannel(sign);
                rabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
            });
        });
        return CommonResult.success(previewList.size());
    }

    @Override
    public List<String> getAllSign(){
        List<String> strings = new ArrayList<>();
        String s = redisService.get(RedisConstants.MSG_ALL_SIGN_KEY);
        if(StringUtils.isEmpty(s)){
            String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/smsManage/getAllSign");
            CommonResult commonResult = JSON.parseObject(result, CommonResult.class);
            if("200".equals(String.valueOf(commonResult.getCode()))){
                Object data = commonResult.getData();
                strings = JSON.parseArray(JSON.toJSONString(data), String.class);
                redisService.set(RedisConstants.MSG_ALL_SIGN_KEY,JSON.toJSONString(strings),60);
            }
        }else {
            strings = JSON.parseArray(s, String.class);
        }
        return strings;
    }
}
